package com.runlooker.runer.ui.home.message;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.jivesoftware.smack.XMPPException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.runlooker.runer.R;
import com.runlooker.runer.application.MyApplication;
import com.runlooker.runer.dao.PersonInfoDao;
import com.runlooker.runer.dao.PresenceDao;
import com.runlooker.runer.dao.RosterEntryDao;
import com.runlooker.runer.entity.LocalRosterEntity;
import com.runlooker.runer.entity.PersonInfoEntity;
import com.runlooker.runer.entity.PresenceEntity;
import com.runlooker.runer.interfaces.PresenceChangeListener;
import com.runlooker.runer.service.XmppService;
import com.runlooker.runer.ui.base.BaseFragement;
import com.runlooker.runer.ui.home.HomeActivty;
import com.runlooker.runer.util.L;

public class MessageFragment extends BaseFragement implements
		PresenceChangeListener {

	private static final String tag = MessageFragment.class.getSimpleName();
	private static final int REFRESH_UI = 1;// 刷新UI
	private ListView mListView;
	private View mNewsLayout;
	private List<Object> mPresenceEntities = new CopyOnWriteArrayList<Object>();
	private PresenceDao mPresenceDao;
	private PersonInfoDao mPersonInfoDao;
	private RosterEntryDao mRosterEntryDao;
	private MyAdapter mMyAdapter;
	private XmppService mXmppService;
	private HomeActivty mHomeActivty;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case REFRESH_UI:
				refreshUI();
				break;

			default:
				break;
			}
		}

	};

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mHomeActivty = (HomeActivty) activity;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		XmppService.removePresenceChangelistener(this);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mNewsLayout = inflater.inflate(R.layout.fragment_message, null);
		initialize();
		return mNewsLayout;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		XmppService.addPresenceChangelistener(this);
	}

	private void initialize() {
		mPersonInfoDao = new PersonInfoDao(getActivity());
		mPresenceDao = new PresenceDao(getActivity());
		mRosterEntryDao = new RosterEntryDao(getActivity());
		mPresenceEntities = mPresenceDao
				.getListByPresenceType(PresenceEntity.subscribe);
		mListView = (ListView) mNewsLayout.findViewById(R.id.lv_message_list);
		mMyAdapter = new MyAdapter(getActivity());
		mMyAdapter.setData(mPresenceEntities);
		mListView.setAdapter(mMyAdapter);
	}

	private void refreshUI() {
		List<Object> list = mPresenceDao
				.getListByPresenceType(PresenceEntity.subscribe);
		mMyAdapter.setData(list);
		mMyAdapter.notifyDataSetChanged();
	}

	class MyAdapter extends BaseAdapter {
		private List<Object> list = new ArrayList<Object>();
		private LayoutInflater mLayoutInflater;
		private PersonInfoEntity info;
		private Object entity;
		private int mPosition;

		public MyAdapter(Context context) {
			mLayoutInflater = LayoutInflater.from(context);
		}

		public void setData(List<Object> list2) {
			this.list = list2;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			this.mPosition = position;
			View view = convertView;
			entity = list.get(position);
			info = mPersonInfoDao.getPersonInfo(((PresenceEntity) entity)
					.getFromAccount());
			ViewHolder holder = new ViewHolder();
			if (view == null) {
				view = mLayoutInflater.inflate(R.layout.new_friend_apply_item,
						null);
				holder.agreeBtn = (Button) view
						.findViewById(R.id.tv_apply_item_agree);
				holder.filed = (TextView) view
						.findViewById(R.id.tv_apply_item_filed);
				holder.nickname = (TextView) view
						.findViewById(R.id.tv_apply_item_nickname);
				holder.headImage = (ImageView) view
						.findViewById(R.id.tv_apply_item_head_image);
				holder.notAgreeBtn = (Button) view
						.findViewById(R.id.tv_apply_item_notagree);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}

			if (info != null) {
				holder.filed.setText(((info.getField() == null)
						|| (info.getField().trim().equals("null")) ? info
						.getField() : ""));
				holder.nickname.setText(((info.getNickName() == null)
						|| (info.getNickName().trim().equals("null")) ? info
						.getNickName() : ""));
			}
			holder.notAgreeBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					list.remove(mPosition);
					mPresenceDao.deleInfoByAccount(((PresenceEntity) entity)
							.getFromAccount());
					notifyDataSetChanged();
				}
			});
			holder.agreeBtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								mXmppService = mHomeActivty.getService();
								mXmppService.addRosterItem(
										((PresenceEntity) entity)
												.getFromAccount(),
										((PresenceEntity) entity)
												.getFromAccount());
								list.remove(mPosition);
								mPresenceDao
										.deleInfoByAccount(((PresenceEntity) entity)
												.getFromAccount());
								mHandler.sendEmptyMessage(REFRESH_UI);
							} catch (XMPPException e) {
								e.printStackTrace();
							}

						}
					}).start();
				}
			});
			return view;
		}

		class ViewHolder {
			TextView nickname;
			TextView filed;
			ImageView headImage;
			Button agreeBtn;
			Button notAgreeBtn;
		}
	}

	@Override
	public void PresenceChange(PresenceEntity entity) {
		LocalRosterEntity rosterEntity = mRosterEntryDao.getRoster(entity
				.getFromAccount());
		if (rosterEntity == null) {
			mHandler.sendEmptyMessage(REFRESH_UI);
			return;
		}
		// 已经成功订阅A，则不再显示A订阅自己的请求（默认自动允许被A订阅）
		if (rosterEntity.getItemType() == LocalRosterEntity.TO
				|| rosterEntity.getItemType() == LocalRosterEntity.BOTH) {
			mPresenceDao.deleInfoByAccount(entity.getFromAccount());
		} else {
			mHandler.sendEmptyMessage(REFRESH_UI);
			L.i(tag, "刷新UI");
		}
	}

}
